package com.wontube.smr.remote.youtube;


import com.wontube.core.annotation.NoLoginSupport;
import com.wontube.core.pub.ServerContext;
import com.wontube.core.pub.servlet.handlers.BasicHandler;
import com.wontube.smr.bo.sites.analizers.YouTubeVideoAnalizer;
import com.wontube.smr.bo.sites.youtube.Mp3BO;
import com.wontube.smr.client.model.vo.AudioFile;
import com.wontube.smr.client.youtube.IAudioHandler;
import com.wontube.smr.model.vo.Progress;
import com.wontube.smr.pub.IObjectListener;


/**
 * @author yuechao
 *
 */
@NoLoginSupport
public class AudioHandler extends BasicHandler implements IAudioHandler {
	/*
	 * @see smr.client.youtube.IAudioHandler#getMp3(java.lang.String)
	 */
	@Override
	public AudioFile getMp3(String url) {
		return this.getYouTubeMp3(url);
	}

	/*
	 * @see smr.client.youtube.IAudioHandler#getYouTubeMp3(java.lang.String)
	 */
	@Override
	public AudioFile getYouTubeMp3(String url) {
		AudioFile audioFile = new AudioFile();
		String videoId = YouTubeVideoAnalizer.getVideoId(url);
		String pageUrl = "http://www.youtube.com/watch?v=" + videoId;

		if ("".equals(pageUrl)) {
			super.getContext().error("Please Enter the Valid YouTube URL.");
			return audioFile;
		}
		
		// 注意Context一定不要在Listener内取，那样取的不一定是当前用户的
		final Mp3BO bo = Mp3BO.getBO(pageUrl);
		final ServerContext context = super.getContext();
		
		IObjectListener<Progress> listener = new IObjectListener<Progress>() {
			@Override
			public void onError(String msg) {
				context.error(msg);
			}
			
			@Override
			public void onMessage(Progress progress) {
			}
		};
		
		bo.addListener(listener);
		try {
			bo.getMp3(audioFile);
		} finally {
			bo.removeListener(listener);
		}
		
		return audioFile;
	}
}
